package com.bbx.taxi.client.Activity.Order;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;

import com.alipay.android.phone.mrpc.core.v;
import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.passanger.OrderDetailBuild;
import com.bbx.api.sdk.model.passanger.Return.CancelReasonList;
import com.bbx.api.sdk.model.passanger.Return.OrderDetails;
import com.bbx.api.sdk.model.passanger.Return.CancelReasonList.CancelReason;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.Locations;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrderList;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.OrderDetailNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Main.MainActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute.CjType;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_STATUS;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_TYPE;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.OrderCencelDB;
import com.bbx.taxi.client.Task.CancelReasonListTask;
import com.bbx.taxi.client.Util.AgainOrder;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.Util.IsDataFail;
import com.bbx.taxi.client.Util.RequestUtils;

public class OrderCancelReason extends BaseBBXActivity{
	@Bind(R.id.sliding_card_content_view)
	RelativeLayout sliding_card_content_view;
	@Bind(R.id.layout_driver)
	LinearLayout layout_driver;
	/** 司机名称 */
	@Bind(R.id.tv_drivername)
	TextView tv_drivername;
	/** 车牌号 */
	@Bind(R.id.tv_car_no)
	TextView tv_car_no;
	/** 时间 */
	@Bind(R.id.tv_time)
	TextView tv_time;
	/** 订单类型 */
	@Bind(R.id.order_type)
	TextView tv_order_type;
	/** 人数 */
	@Bind(R.id.tv_count)
	TextView tv_count;
	/** 出发地 */
	@Bind(R.id.tv_start)
	TextView tv_start;
	/** 目的地 */
	@Bind(R.id.tv_end)
	TextView tv_end;
	@Bind(R.id.tv_reason)
	TextView tv_reason;
	@Bind(R.id.btn_confirm)
	Button btn_confirm;
	@Bind(R.id.tv_rating)
	TextView tv_rating;
	@Bind(R.id.rb_rating)
	RatingBar rb_rating;
	private MyOrderDB db_myorder;// 我的订单数据库
	private OrderCencelDB db_cencel;// 取消订单数据库
	private MyOrderList mMyOrderList;
	private String order_id;
	private String reason;
	private int order_type,order_origin;
	private int viewId;
	private OrderDetailTask mOrderDetailTask;
	private CancelReasonListTask mCancelReasonListTask;
	private List<CancelReason> list;

	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_cancel_reason);
		super.onCreate(savedInstanceState);
		
	}

	@Override
	protected void initView() {
		setTitle(getString(R.string.order_detail));
		db_myorder = new MyOrderDB();
		db_cencel = new OrderCencelDB();
		btn_confirm.setOnClickListener(this);
		sliding_card_content_view.setVisibility(View.GONE);
		list=new ArrayList<CancelReason>();
		setCancelReason();
		try {
			initView2();
			onLoadDate();
		} catch (Exception e) {
			onLoadDate();
		}
	}

	public void initView2() {
		Intent intent = getIntent();
		if (intent.getExtras() != null) {
			order_id = intent.getExtras().getString(OrderMsg.extra_order_id);
		} else {
			ToastUtil.showToast(context, R.string.error);
			finish();
			return;
		}
		new AsyncTask<Void, Void, Void>(){
			@Override
			protected Void doInBackground(Void... params) {
				mMyOrderList = db_myorder.onReadDB(order_id);
				reason = db_cencel.onGetReason(order_id);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if (reason == null || reason.equals("")) {
					tv_reason.setText(R.string.order_canceled);
				} else {
					if (mMyOrderList.getOrder_status() == Value.ORDER_STATUS_KF_CANCEL) {
						tv_reason.setText(getString(R.string.order_canceled) + "\n"
								+ String.format(getString(R.string.reason), reason));
					} else {
						tv_reason.setText(String.format(
								getString(R.string.cancel_reason), reason));
					}
					
				}
				setView();
				super.onPostExecute(result);
			}
		    	
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}
	public void setView(){
		MainAttribute main=MainAttribute.getInstance();
		if(mMyOrderList.getDriver_id()!=null&&!mMyOrderList.getDriver_id().equals("")){
			tv_drivername.setText(mMyOrderList.getDriver_name());
			tv_car_no.setText(mMyOrderList.getCar_NO());
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(1);// 保留小数点1位
			tv_rating.setText(FormatUtil.onFormatStar((float) mMyOrderList
					.getDriver_star()) + "");
			rb_rating.setRating((float) mMyOrderList.getDriver_star());
			layout_driver.setVisibility(View.VISIBLE);
		}else{
			layout_driver.setVisibility(View.GONE);
		}

		//由于时间容易出现空
		if(mMyOrderList.getAppoint_time()==null){
			onLoadDate();
			return;
		}
		tv_time.setText(DateFormat.onDateRemove_ss(mMyOrderList
				.getAppoint_time()));
		order_type = mMyOrderList.getOrder_type();
		order_origin=mMyOrderList.getOrder_origin();
		switch (order_type) {
		case Value.ORDER_TYPE_SN:
			tv_order_type.setText(R.string.sn);
			viewId = Value.VIEWID_SN;
			tv_count.setVisibility(View.GONE);
			break;
		case Value.ORDER_TYPE_KJ:
			tv_order_type.setText(R.string.kj);
			viewId = Value.VIEWID_KJ;
//			tv_count.setText(String.format(getString(R.string.num_jian),
//					mMyOrderList.getLocations().getCount()));
			break;
		case Value.ORDER_TYPE_PC:
			tv_order_type.setText(R.string.pc);
			viewId = Value.VIEWID_PC;
			main.setCjType(CjType.PC);
			tv_count.setText(String.format(getString(R.string.num),
					mMyOrderList.getLocations().getCount()));
			break;
		case Value.ORDER_TYPE_BC:
			tv_order_type.setText(R.string.bc);
			tv_count.setText(String.format(getString(R.string.num_car),
					mMyOrderList.getLocations().getCount()));
			viewId = Value.VIEWID_PC;
			main.setCjType(CjType.BC);
			break;
		}
		switch(order_origin){
		   case Value.ORDER_ORIGIN:
			   tv_order_type.setText(R.string.aixin);
				viewId = Value.VIEWID_PC;
				tv_count.setVisibility(View.GONE);
				btn_confirm.setVisibility(View.GONE);
			   break;
		   case Value.ORDER_ORIGIN_SF:
				tv_order_type.setText(R.string.sf);
				viewId = Value.VIEWID_PC;
				main.setCjType(CjType.SF);
				tv_count.setText(String.format(getString(R.string.num),
						mMyOrderList.getLocations().getCount()));
			   break;
		}
		//显示爱心直通车
		if(order_origin==Value.ORDER_ORIGIN){
			
		}
		tv_start.setText(mMyOrderList.getLocations().getStart().getAddress());
		tv_end.setText(mMyOrderList.getLocations().getEnd().getAddress());
		sliding_card_content_view.setVisibility(View.VISIBLE);
	}
     /**
     * 开始加载数据
     */
    public void onLoadDate(){
 		RequestUtils.requestCancelReasonList(context);
     }
	/**
	 * 设置本地的取消原因
	 */
	public void setCancelReason() {
		if (list != null) {
			list.clear();
			CancelReason mCancelReason = new CancelReasonList().new CancelReason();
			mCancelReason.setId(1);
			mCancelReason.setReason(this.getResources().getString(
					R.string.cancel_reason1));
			list.add(mCancelReason);
			mCancelReason = new CancelReasonList().new CancelReason();
			mCancelReason.setId(2);
			mCancelReason.setReason(this.getResources().getString(
					R.string.cancel_reason2));
			list.add(mCancelReason);
			mCancelReason = new CancelReasonList().new CancelReason();
			mCancelReason.setId(3);
			mCancelReason.setReason(this.getResources().getString(
					R.string.cancel_reason3));
			list.add(mCancelReason);
		}

	}

	/**
	 * 获取订单详情
	 */
	public void getOrderDetail(String order_id) {
		OrderDetailBuild mOrderDetail = new OrderDetailBuild(context);
		mOrderDetail.uid = mApplication.getUid();
		mOrderDetail.access_token = mApplication.getToken();
		mOrderDetail.order_id = order_id;
		mOrderDetailTask = new OrderDetailTask(context, mOrderDetail);
		mOrderDetailTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * 订单详情
	 */
	private class OrderDetailTask extends BaseAsyncTask {

		private OrderDetailBuild mOrderDetail;

		public OrderDetailTask(Activity context, OrderDetailBuild mOrderDetail) {
			super(context);
			this.mOrderDetail = mOrderDetail;
		}

		@Override
		public void onSuccess(int status,Object object) {
			if (object != null) {
				OrderDetails mOrderDetails = (OrderDetails) object;
				if (mOrderDetails != null) {
					mMyOrderList = mOrderDetails.getDetails();
					int reason_id =mMyOrderList.getReason_type();
					String reason = mMyOrderList
							.getCancel_reason();
					setOnCancelReason(reason_id, reason);
					setView();
				}

			} else {
				ToastUtil.showToast(context, R.string.no_network);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			finish();
			ToastUtil.showToast(context,
					getResources().getString(R.string.no_network));
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mOrderDetail).getJson();
			return new OrderDetailNet(context, json);
		}
	}

	/**
	 * 设置取消原因
	 */
	public void setOnCancelReason(int reason_id, String reason) {
		if (reason == null||reason.equals("")) {
			tv_reason.setText(R.string.order_canceled);
		} else if (reason_id == 0 && reason != null && reason.equals("")) {
			tv_reason.setText(R.string.order_canceled);
		} else {
			String type = "";
			for (int i = 0; i < list.size(); i++) {
				if (reason_id == list.get(i).getId()) {
					type = list.get(i).getReason();
					break;
				} else if (reason_id == (i + 1)) {
					type = list.get(i).getReason();
					break;
				}
			}
			if (mMyOrderList.getOrder_status() == Value.ORDER_STATUS_KF_CANCEL) {
				tv_reason.setText(getString(R.string.order_canceled) + "\n"
						+ String.format(getString(R.string.reason), reason));
			} else {
//				tv_reason.setText(String.format(
//						getString(R.string.cancel_reason),
//						(type.equals("") ? "" : type + ";") + reason));
				tv_reason.setText(String.format(
						getString(R.string.cancel_reason),
						(type.equals("") ? "" : "" ) + reason));
				
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_left:
			finish();
			break;
		case R.id.btn_confirm:
			AgainOrder.onAgainOrder(this, mMyOrderList, viewId);
			break;
		}
		super.onClick(v);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	public void finish() {
		setResult(resultCode, new Intent());
		super.finish();
	}

	@Override
	protected void onDestroy() {
		if (mOrderDetailTask != null
				&& mOrderDetailTask.getStatus() != AsyncTask.Status.FINISHED)
			mOrderDetailTask.cancel(true);
		super.onDestroy();
	}

	@Override
	public void onNotify(int type,JSONObject jb,Msgs.Data msgs_data){
		if(msgs_data!=null&&msgs_data.getOrder_id()!=null&&msgs_data.getOrder_id().equals(order_id)){
			return ;
		}
		super.onNotify(type, jb,msgs_data);
	}
	@Override
	public void onNotifyData(DATA_STATUS data_status, DATA_TYPE data_type, int status,Object object) {
		  switch(data_type){
	        case CANCELREASON:
	        	if (IsDataFail.isDataFail(data_status)) {
	                return;
	            }
	    		String cancel_reason_json = SharedPreUtil.getStringValue(this,
	    				SharedPreEncryptUtil.cancel_reason_json, "");
	    		CancelReasonList mCancelReasonList = (CancelReasonList) new JsonBuild()
	    				.getData(CancelReasonList.class, cancel_reason_json);
	    		if (list != null && mCancelReasonList != null) {
	    			list.clear();
	    			list.addAll(mCancelReasonList.getList());
	    		}
	    		getOrderDetail(order_id);
	    	break;
	       }
	}
}
